package com.example.testnetty.nettyserver;


import android.util.Log;

import java.util.Iterator;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChannelGroups {


    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //添加一个管道（通道）
    public static void add(Channel channel) {
        CHANNEL_GROUP.add(channel);
    }

    //广播所有消息
    public static ChannelGroupFuture broadcast(Object msg) {


        return CHANNEL_GROUP.writeAndFlush(msg, new ChannelMatchers());
    }

    public static Iterator<Channel> allChanel() {

        return CHANNEL_GROUP.iterator();
    }

    //发送到某个客户端
    public static ChannelFuture broadOne(Channel channel, Object o) {
        for (Channel channel0 : CHANNEL_GROUP) {
            if (channel0.equals(channel)) {
                Log.e("nettyServer","查到数据");
                return channel.writeAndFlush(o + "\r\n");
            } else {
                Log.e("nettyServer","没有查到数据");
            }
        }
        return null;
    }


    //发送到某个客户端
    public static ChannelFuture SendSpecifyClient(ChannelId channelid, Object o) {

        Log.e("nettyServer","发送到某个客户端数据:    " + o);

        return CHANNEL_GROUP.find(channelid).writeAndFlush(o);

    }

    //广播所有消息
    public static ChannelGroupFuture broadcast(Object msg, ChannelMatcher matcher) {
        return CHANNEL_GROUP.writeAndFlush(msg, matcher);
    }


    //刷新
    public static ChannelGroup flush() {
        return CHANNEL_GROUP.flush();
    }

    public static ChannelGroup write(Object o) {
        return CHANNEL_GROUP.write(o).group();
    }

    public static ChannelGroup writeAndFlush(Object o) {
        return CHANNEL_GROUP.writeAndFlush(o).group();
    }

    //移除一个通道
    public static boolean discard(Channel channel) {
        return CHANNEL_GROUP.remove(channel);
    }

    //断开连接
    public static ChannelGroupFuture disconnect() {
        return CHANNEL_GROUP.disconnect();
    }

    //断开连接
    public static ChannelGroupFuture disconnect(ChannelMatcher matcher) {
        return CHANNEL_GROUP.disconnect(matcher);
    }

    //包含
    public static boolean contains(Channel channel) {
        return CHANNEL_GROUP.contains(channel);
    }

    //管道的大小（Socket连接数量）
    public static int size() {
        return CHANNEL_GROUP.size();
    }

    private static class ChannelMatchers implements ChannelMatcher {

        public boolean matches(Channel channel) {
            return true;
        }
    }


}